package com.uu.ssm.util;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class Generator {

    public static void main(String[] args) {
        try {
            // 加载数据库配置文件
            Properties properties = new Properties();
            FileInputStream inputStream = new FileInputStream("src/main/resources/db.properties");
            properties.load(inputStream);

            // 获取数据库配置信息
            String driver = properties.getProperty("dataSource.driver", "com.mysql.cj.jdbc.Driver");
            String url = properties.getProperty("dataSource.url");
            String username = properties.getProperty("dataSource.username");
            String password = properties.getProperty("dataSource.password");

            if (url == null || username == null || password == null) {
                throw new IllegalArgumentException("数据库配置信息不能为空！");
            }

            // 加载 MyBatis Generator 配置文件
            List<String> warnings = new ArrayList<>();
            File configFile = new File(Generator.class.getClassLoader().getResource("generatorConfig.xml").toURI());
            ConfigurationParser cp = new ConfigurationParser(properties, warnings); // 将 properties 传递给 ConfigurationParser
            Configuration config = cp.parseConfiguration(configFile);

            // 创建并运行 MyBatis Generator
            DefaultShellCallback shellCallback = new DefaultShellCallback(true);
            MyBatisGenerator generator = new MyBatisGenerator(config, shellCallback, warnings);
            generator.generate(null);

            System.out.println("MyBatis Generator completed!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("MyBatis Generator failed!");
        }
    }
}
